package fun.tan90.easy.binlog.plugin.redis.single.config;

import com.github.benmanes.caffeine.cache.CacheLoader;
import fun.tan90.easy.binlog.plugin.common.constants.DamiEventConstants;
import fun.tan90.easy.binlog.plugin.common.model.OutputParam;
import fun.tan90.easy.binlog.plugin.redis.common.constants.RedisPluginConstants;
import fun.tan90.easy.binlog.plugin.redis.single.model.RedisSingleParams;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.noear.dami.Dami;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;
import java.util.Objects;

/**
 * description 动态连接mqtt
 * company 铁人科技
 *
 * @author Li YuLong
 * @date 2023/8/17 10:56
 */
@Slf4j
public class RedisSingleCacheLoader implements CacheLoader<String, JedisPool> {

    @Override
    public @Nullable JedisPool load(@NonNull String outputCode) throws Exception {
        OutputParam outputParam = Dami.<String, OutputParam>bus().sendAndRequest(DamiEventConstants.OUTPUT_PARAM_TOPIC, outputCode);
        if (Objects.isNull(outputParam)) {
            return null;
        }
        RedisSingleParams redisSingleParams = (RedisSingleParams) outputParam;
        // 创建连接池配置对象
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMinIdle(redisSingleParams.getMinIdle());   // 设置最小空闲连接数
        poolConfig.setMaxIdle(redisSingleParams.getMaxIdle());   // 设置最大空闲连接数
        poolConfig.setMaxTotal(redisSingleParams.getMaxTotal()); // 设置最大连接数
        poolConfig.setMaxWait(Duration.ofMillis(redisSingleParams.getMaxWait()));   // 设置从连接池获取连接的最大等待时间

        String host = redisSingleParams.getHost();
        int port = redisSingleParams.getPort();
        int timeout = redisSingleParams.getTimeout();
        int soTimeout = RedisPluginConstants.SO_TIMEOUT;
        String user = StringUtils.hasLength(redisSingleParams.getUser()) ? redisSingleParams.getUser() : null;
        String password = StringUtils.hasLength(redisSingleParams.getPassword()) ? redisSingleParams.getPassword() : null;
        int database = redisSingleParams.getDatabase();
        return new JedisPool(poolConfig, host, port, timeout, soTimeout, user, password, database, "eb_redis");
    }
}